import { create } from "zustand"
import { createJSONStorage, persist } from "zustand/middleware"

import type {
  AccessToken,
  TokenAction,
  TokenState,
  TokenType
} from "~type/tokenType"
import { StoreageKEY } from "~util/const"
import { storage } from "~util/sotrage"

export const useTokenStroe = create<TokenState & TokenAction>()(
  persist(
    (set, get) => ({
      aiSource: "",
      grantType: "client_credentials",
      apiKey: "",
      secretKey: "",
      refresh_token: "",
      expires_in: "",
      session_key: "",
      access_token: "",
      scope: "",
      session_secret: "",
      createTime: new Date().getTime(),
      tokenType: {},
      accessToken: {},
      async setToken(token: AccessToken) {
        set({ accessToken: { ...token }, createTime: new Date().getTime() })
      },
      setReqToken(reToken: TokenType) {
        set({ tokenType: { ...reToken }, createTime: new Date().getTime() })
      },
      dellAllToken() {
        set({})
      }
    }),
    {
      name: StoreageKEY.tokenObj,
      storage: createJSONStorage(() => storage),
      onRehydrateStorage: (state) => {
        console.log("hydration starts") //水合开始

        // 可选
        return (state, error) => {
          if (error) {
            console.log("an error happened during hydration", error) //水合过程中发生错误
          } else {
            console.log("hydration finished") //水合完成
          }
        }
      }
      // serialize: (state) => btoa(JSON.stringify(state)),
      // deserialize: (str) => JSON.parse(atob(str))
    }
  )
)
